package com.zyx.camunda.controller;

import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Yaxi.Zhang
 * @since 2022/9/15 23:24
 */
@RestController
@RequestMapping("/flow")
public class WorkflowController {

    private final RepositoryService repositoryService;
    private final RuntimeService runtimeService;
    private final IdentityService identityService;

    public WorkflowController(RepositoryService repositoryService, RuntimeService runtimeService, IdentityService identityService) {
        this.repositoryService = repositoryService;
        this.runtimeService = runtimeService;
        this.identityService = identityService;
    }

    @GetMapping("/deploy")
    public String deploy() {
        Deployment deploy = repositoryService.createDeployment()
                .name("部署第一个流程")
                .addClasspathResource("process.bpmn")
                .deploy();
        return deploy.getId() + ":" + deploy.getName();
    }

    @GetMapping("/start/{processKey}")
    public String start(@PathVariable(value = "processKey") String processKey) {
        identityService.setAuthenticatedUserId("xiaoming");
        VariableMap variables = Variables.createVariables();
        // variables.putValue("isFree", false);
        variables.putValue("originDays", 10);
        runtimeService.startProcessInstanceByKey(processKey, variables);
        identityService.setAuthentication(null);
        return "success";
    }

}
